package info.zlong.visibleruntime.core;

import java.util.Stack;
import info.zlong.visibleruntime.core.model.LogMsg;
import info.zlong.visibleruntime.core.util.StringUtils;

public class LogMsgHolder {
	private String id = "";
	private int inc = 0;
	private Stack<KeyPath> paths = new Stack<KeyPath>();
	private LogMsg logMsg = new LogMsg();
	
	public LogMsgHolder setId(String id){
		this.id = id;
		this.inc=0;
		this.paths = new Stack<KeyPath>();
		
		
		return this;
	}
	
	public String getLog(String key,String msg){
		String log = getStartLog(key, msg);
		paths.pop();
		return log;
	}

	public String getStartLog(String key,String msg){
		if(StringUtils.isEmpty(key)){
			key = getInckey();
		}
		
		String path = String.format("_children.%s",key);
		if(!paths.isEmpty()){
			path =String.format("%s._children.%s",paths.peek().getPath(),key);
		}
		paths.push(new KeyPath(key, path));
		
		return logMsg.toJson(id, path, msg, LogMsg.START);
	}
	
	public String getEndLog(String key,String msg){
		
		String path;
		if(StringUtils.isEmpty(key)){
			if(!paths.isEmpty()){
				path =paths.pop().getPath();
			}else{
				path = getInckey();
			}
		}else{
			path = key;
			if(constainsKey(key)){
				while(!paths.isEmpty()){
					KeyPath keyPath = paths.pop();
					if(keyPath.getKey().equals(key)){
						path = keyPath.getPath();
						break;
					}
				}
			}
		}
		
		return logMsg.toJson(id, path, msg, LogMsg.END);
	}

	private String getInckey() {
		return String.format("key%d", this.inc++);
	}

	private boolean constainsKey(String key) {
		if(!paths.isEmpty()){
			for(int i = paths.size() -1 ;i >= 0;i--){		//最后一个的情况居多,所以使用逆向遍历
				if(paths.get(i).getKey().equals(key)){
					return true;
				};
			}
		}
		return false;
	}

	public String getEndLog(String msg) {
		KeyPath path = null;
		if(!paths.isEmpty()){
			path =paths.peek();
		}
		
		return logMsg.toJson(id, path.getPath(), msg, LogMsg.END);
	}
	
	static class KeyPath{
		String key;
		String path;
		
		public KeyPath(String key,String path){
			this.key = key;
			this.path = path;
		}

		public String getKey() {
			return key;
		}

		public String getPath() {
			return path;
		}
		
		
	}
}
